<script setup>
  import { ref, reactive, computed, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import useUserStore from '@/stores/user'

  // 获取用户store
  const userStore = useUserStore()

  // 分页相关数据
  const currentPage = ref(1)
  const pageSize = ref(5)
  const size = ref('small')
  const disabled = ref(true)
  const background = ref(true)
  const total = ref(0)
  const loading = ref(false)

  // 搜索表单数据
  const searchForm = reactive({
    username: ''
  })

  // 搜索结果数据（用于点击搜索后显示结果）
  const searchResults = ref([])
  const isSearching = ref(false)

  // 选中的用户列表
  const selectedUsers = ref([])

  // 编辑和添加用户的对话框
  const dialogVisible = ref(false)
  const dialogTitle = ref('添加用户')
  const isEdit = ref(false)

  // 用户表单数据
  const userForm = reactive({
    userId: '',
    username: '',
    password: '',
    roles: []
  })

  // 用户表单校验规则
  const rules = reactive({
    username: [
      { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    password: [
      { required: !isEdit, message: '请输入密码', trigger: 'blur' },
      { min: 6, max: 20, message: '密码长度在6到20个字符之间', trigger: 'blur' }
    ]
  })

  // 用户表单引用
  const userFormRef = ref(null)

  // 初始化数据
  onMounted(() => {
    // 确保使用store中的用户数据
    total.value = userStore.userInfo.length
  })

  // 计算当前页显示的用户列表
  const currentPageUsers = computed(() => {
    // 根据是否处于搜索状态决定使用哪个数据源
    const sourceData = isSearching.value ? searchResults.value : userStore.userInfo
    total.value = sourceData.length

    // 计算分页数据
    const start = (currentPage.value - 1) * pageSize.value
    const end = start + pageSize.value
    return sourceData.slice(start, end)
  })

  // 处理搜索
  const handleSearch = () => {
    if (!searchForm.username.trim()) {
      ElMessage.warning('请输入搜索内容')
      return
    }

    loading.value = true

    // 模拟异步搜索过程
    setTimeout(() => {
      searchResults.value = userStore.userInfo.filter(user =>
        user.username.includes(searchForm.username.trim())
      )
      isSearching.value = true
      currentPage.value = 1

      if (searchResults.value.length === 0) {
        ElMessage.info('没有找到匹配的用户')
      } else {
        ElMessage.success(`找到 ${searchResults.value.length} 个匹配的用户`)
      }

      loading.value = false
    }, 300)
  }

  // 处理重置
  const handleReset = () => {
    searchForm.username = ''
    isSearching.value = false
    currentPage.value = 1
    selectedUsers.value = []
    disabled.value = true
  }

  // 处理添加用户
  const handleAddUser = () => {
    dialogTitle.value = '添加用户'
    isEdit.value = false
    Object.assign(userForm, {
      userId: '',
      username: '',
      password: '',
      roles: []
    })
    dialogVisible.value = true
  }

  // 处理编辑用户
  const handleEditUser = (user) => {
    dialogTitle.value = '编辑用户'
    isEdit.value = true
    Object.assign(userForm, {
      userId: user.userId,
      username: user.username,
      password: '', // 编辑时不显示密码
      roles: [...user.roles] // 深拷贝角色数组
    })
    dialogVisible.value = true
  }

  // 处理删除用户
  const handleDeleteUser = (userId) => {
    // 显示确认对话框
    ElMessageBox.confirm('确定要删除该用户吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      loading.value = true

      // 模拟异步删除过程
      setTimeout(() => {
        // 使用store中的deleteUser方法删除用户
        const success = userStore.deleteUser(userId)

        if (success) {
          // 如果正在搜索，同步更新搜索结果
          if (isSearching.value) {
            const searchIndex = searchResults.value.findIndex(user => user.userId === userId)
            if (searchIndex !== -1) {
              searchResults.value.splice(searchIndex, 1)
            }
          }

          // 如果删除了当前页的最后一条数据，自动回退到上一页
          if (currentPageUsers.value.length === 0 && currentPage.value > 1) {
            currentPage.value--
          }

          ElMessage.success('用户删除成功')
        }

        // 清空选中状态
        selectedUsers.value = []
        disabled.value = true
        loading.value = false
      }, 500)
    }).catch(() => {
      // 用户取消删除
      ElMessage.info('已取消删除')
    })
  }

  // 处理批量删除
  const handleBatchDelete = () => {
    if (selectedUsers.value.length === 0) {
      ElMessage.warning('请选择要删除的用户')
      return
    }

    ElMessageBox.confirm(`确定要删除选中的 ${selectedUsers.value.length} 个用户吗？`, '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      loading.value = true

      // 模拟异步删除过程
      setTimeout(() => {
        // 使用store中的deleteUsers方法批量删除用户
        userStore.deleteUsers(selectedUsers.value)

        // 如果正在搜索，同步更新搜索结果
        if (isSearching.value) {
          searchResults.value = searchResults.value.filter(user =>
            !selectedUsers.value.includes(user.userId)
          )
        }

        // 如果删除了当前页的所有数据，自动回退到上一页
        if (currentPageUsers.value.length === 0 && currentPage.value > 1) {
          currentPage.value--
        }

        // 清空选中状态
        selectedUsers.value = []
        disabled.value = true

        ElMessage.success(`成功删除 ${selectedUsers.value.length} 个用户`)
        loading.value = false
      }, 500)
    }).catch(() => {
      ElMessage.info('已取消删除')
    })
  }

  // 处理选择用户变化
  const handleSelectionChange = (selection) => {
    selectedUsers.value = selection.map(user => user.userId)
    disabled.value = selectedUsers.value.length === 0
  }

  // 处理表单提交
  const handleSubmit = async () => {
    try {
      // 验证密码规则 - 由于isEdit是响应式的，需要手动检查
      if (!isEdit && !userForm.password) {
        ElMessage.error('请输入密码')
        return
      }

      if (!isEdit && (userForm.password.length < 6 || userForm.password.length > 20)) {
        ElMessage.error('密码长度在6到20个字符之间')
        return
      }

      loading.value = true

      // 模拟异步提交过程
      setTimeout(() => {
        const now = new Date().toLocaleString('zh-CN')

        if (isEdit.value) {
          // 编辑用户
          const index = userStore.userInfo.findIndex(user => user.userId === userForm.userId)
          if (index !== -1) {
            userStore.userInfo[index] = {
              ...userStore.userInfo[index],
              username: userForm.username,
              roles: userForm.roles,
              updateTime: now
            }

            // 如果正在搜索，同步更新搜索结果
            if (isSearching.value) {
              const searchIndex = searchResults.value.findIndex(user => user.userId === userForm.userId)
              if (searchIndex !== -1) {
                searchResults.value[searchIndex] = { ...userStore.userInfo[index] }
              }
            }

            ElMessage.success('用户更新成功')
          }
        } else {
          // 添加用户
          // 检查用户名是否已存在
          const userExists = userStore.userInfo.some(user => user.username === userForm.username)
          if (userExists) {
            ElMessage.error('用户名已存在')
            loading.value = false
            return
          }

          const newUser = {
            userId: Date.now(), // 使用时间戳作为临时ID
            username: userForm.username,
            password: userForm.password,
            avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
            roles: userForm.roles.length > 0 ? userForm.roles : ['普通用户'],
            createTime: now,
            updateTime: now,
            token: `${userForm.username} Token`
          }

          // 使用store中的addUser方法添加用户（添加到列表末尾）
          userStore.addUser(newUser)

          // 如果正在搜索，且新用户符合搜索条件，添加到搜索结果末尾
          if (isSearching.value && newUser.username.includes(searchForm.username.trim())) {
            searchResults.value.push(newUser)
          }

          // 切换到最后一页以显示新添加的用户
          const totalPages = Math.ceil(total.value / pageSize.value)
          currentPage.value = totalPages

          ElMessage.success('用户添加成功')
        }

        // 关闭对话框
        dialogVisible.value = false
        loading.value = false
      }, 500)
    } catch (error) {
      // 表单校验失败
      console.error('表单校验失败:', error)
      loading.value = false
    }
  }

  // 处理对话框关闭
  const handleDialogClose = () => {
    dialogVisible.value = false
  }

  // 处理页码变化
  const handleCurrentChange = (val) => {
    currentPage.value = val
  }

  // 处理每页条数变化
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
  }
</script>

<template>
  <div>
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form
        :inline="true"
        :model="searchForm"
        size="small"
      >
        <el-form-item label="用户名">
          <el-input
            v-model="searchForm.username"
            placeholder="请输入用户名"
            style="width: 240px;"
          />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="handleSearch"
            :loading="loading"
          >
            搜索
          </el-button>
          <el-button
            @click="handleReset"
            :loading="loading"
          >
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 用户表格区域 -->
    <el-card
      class="table-card"
      style="margin-top: 20px;"
    >
      <div
        class="table-header"
        style="margin-bottom: 10px;"
      >
        <el-button
          type="primary"
          @click="handleAddUser"
          style="margin-right: 10px;"
          :loading="loading"
        >
          添加用户
        </el-button>
        <el-button
          type="danger"
          :disabled="disabled"
          @click="handleBatchDelete"
          :loading="loading"
        >
          批量删除
        </el-button>
      </div>

      <el-table
        class="table-content"
        v-loading="loading"
        :data="currentPageUsers"
        style="width: 100%"
        border
        @selection-change="handleSelectionChange"
        size="small"
      >
        <el-table-column
          type="selection"
          width="55"
        />
        <el-table-column
          type="index"
          label="#"
          width="50"
        />
        <el-table-column
          prop="userId"
          label="ID"
          width="80"
        />
        <el-table-column
          prop="username"
          label="用户名"
          min-width="120"
        >
          <template #default="scope">
            <div style="display: flex; align-items: center;">
              <img
                :src="scope.row.avatar"
                alt="用户头像"
                style="width: 30px; height: 30px; border-radius: 50%; margin-right: 10px;"
              >
              {{ scope.row.username }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="roles"
          label="用户角色"
          min-width="100"
        >
          <template #default="scope">
            <el-tag
              v-for="role in scope.row.roles"
              :key="role"
              size="small"
              style="margin-right: 5px;"
            >
              {{ role }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          min-width="160"
        />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="160"
        />
        <el-table-column
          label="操作"
          min-width="120"
          fixed="right"
        >
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditUser(scope.row)"
              style="margin-right: 10px;"
              :loading="loading"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteUser(scope.row.userId)"
              :loading="loading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div
        class="pagination-container"
        style="margin-top: 20px; text-align: right;"
      >
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 30]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :size="size"
          :background="background"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :before-close="handleDialogClose"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <el-form
        ref="userFormRef"
        :model="userForm"
        label-width="100px"
        style="margin-top: 20px;"
        size="small"
      >
        <el-form-item
          label="用户名"
          prop="username"
        >
          <el-input
            v-model="userForm.username"
            placeholder="请输入用户名"
            :disabled="loading"
          />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          v-if="!isEdit"
        >
          <el-input
            v-model="userForm.password"
            type="password"
            placeholder="请输入密码"
            :disabled="loading"
          />
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select
            v-model="userForm.roles"
            multiple
            placeholder="请选择用户角色"
            :disabled="loading"
          >
            <el-option
              v-for="role in userStore.roleList"
              :key="role.roleId"
              :label="role.roleName"
              :value="role.roleName"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button
            @click="handleDialogClose"
            :disabled="loading"
          >
            取消
          </el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="loading"
          >
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
  .search-card {
    height: 70px;
  }


  .table-header {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .table-content {
    max-height: calc(100vh - 325px);
    overflow: auto;
  }
</style>